﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.Admin == "undefined") Axis.Admin = {};
Axis.Admin.Order = {
    Init: function () {
        var thisObj = this;
        thisObj.Grid.Init();
        thisObj.EventClick();
        $("button").button();

    },
    EventClick: function () {
        var thisObj = this;
//        $("#imgUserExport").click(function () {
//            ExportExcel();
//        });
        $("#imgUserDel").click(function () {
            thisObj.DeleteNews();
        });

    },
    Grid: {
        ID: "#GridContents",
        PagesID: "#GridPages",
        Init: function () {
            var thisObj = this;
            var options = {
                url: '../Order/Service/OrderService.ashx?Action=GET&Context=Backend&ProductTypeID=' + ProductTypeID,
                datatype: "json",
                multiselect: true,
                colNames: [
                    'ID', 'Tên khách hàng', 'Điện thoại', 'Email', 'Địa chỉ', 'Giờ đặc', 'Trạng thái', 'Trạng thái', 'Chi tiết', 'Xử lý'
                        ],
                colModel: [
                    { name: 'ID', index: 'ID', width: 1, hidden: true, frozen: true },
                    { name: 'Name', index: 'Page', width: 150, frozen: true, align: 'center' },
                    { name: 'Phone', index: 'Title', width: 100, frozen: true, align: 'center' },
                    { name: 'Email', index: 'Title', width: 200, frozen: true, align: 'center' },
                    { name: 'Address', index: 'Title', width: 300, frozen: true, align: 'center' },
                    { name: 'Time', index: 'Title', width: 150, frozen: true, align: 'center' },
                     { name: 'StatusInt', index: 'Title', width: 1, hidden: true, align: 'center' },
                      { name: 'StatusString', index: 'Title', width: 70, align: 'center' },
                     { name: 'Detail', index: 'Title', width: 70, align: 'center' },
                    { name: 'Action', index: 'Action', width: 55, align: 'center' }

                ],

                gridComplete: function () {

                },
                onCellSelect: function (rowid, iCol, cellcontent, e) {

                },
                onSelectRow: function (rowid, status, e) {

                },
                ondblClickRow: function (rowid, iRow, iCol, e) {

                },
                afterInsertRow: function (rowid, aData, addData) {
                    var action = $.string.Format("<img class='imgAction' src='../../Images/16x16/edit.png' onclick=\"ShowEdit('{0}')\"/>", rowid);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'Action', action);
                    var iconStatus = 's_enable.png';
                    //                    if(aData.Status=='-1')
                    //                     iconStatus='s_delete.png';
                    if (aData.Status == '0')
                        iconStatus = 's_visible.png';
                    var StatusString = $.string.Format("<img class='imgAction' src='../../Images/16x16/{0}' onclick=\"ActionStatus('{1}',{2})\"/>", iconStatus, rowid, aData.Status);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'StatusString', StatusString);
                    var AddImage = $.string.Format("<img class='imgAction' src='../../Images/16x16/{0}' onclick=\"AddImage('{1}',{2})\"/>", 'Add.png', rowid, aData.Status);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'AddImage', AddImage);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'Detail', $.string.Format("<img class='imgAction' src='../../Images/16x16/Preview_16x16.png' onclick=\"ShowOrderDetail('{0}',{1})\"/>", rowid, aData.Status));


                },
                multiselect: true,
                height: 'auto',
                rownumbers: true,
                autowidth: true,
                //forceFit: true,
                shrinkToFit: false,
                rowNum: 20,
                pager: thisObj.PagesID
            };
            thisObj.GridObj = new CGrid(options);
            thisObj.GridObj.Init(thisObj.ID);
            thisObj.GridObj.NavGrid();
            thisObj.GridObj.FrozenColumns();
        },
        Reload: function () {
            var thisObj = this;
            if (thisObj.GridObj)
                thisObj.GridObj.ReloadGrid();
        },
        SelectRow: function () {
            var thisObj = this;
            if (thisObj.GridObj) {
                return thisObj.GridObj.SelectRow();
            }
            return null;
        },
        SetNewUrl: function (url) {
            var thisObj = this;
            thisObj.GridObj.setGridParam({ url: url });
            thisObj.Reload();

        },
        GetRowData: function (id) {
            var thisObj = this;
            return $(thisObj.ID).jqGrid('getRowData', id);
        }
    },
    DialogEdit: {
        ID: "#FormEdit",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            thisObj.ClearForm();
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Chi tiết đơn hàng",
                    width: 700,
                    position: {
                        my: 'top',
                        at: 'top'
                    },
                    open: function () {

                    }
                });
                thisObj.Dialog.Init(thisObj.ID)
            }
            var buttonText = "";
            switch (action) {
                case "INSERT":
                    thisObj.Dialog.SetTitle("Thêm Loại Sản Phẩm");
                    $(thisObj.ID).find("[data-role='INSERT']").show();
                    $(thisObj.ID).find("#txtLoginName").focus();
                    buttonText = "Thêm";
                    break;
                case "UPDATE":
                    thisObj.Dialog.SetTitle("Sửa: " + opts.Code);


                    buttonText = "Chi tiết";
                    break;
            }
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.Order.Update(action, opts);
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Đóng",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        LoadNews: function (opt) {

        },
        ClearForm: function () {
            $("#FormEdit").find("[data-field]").each(function () {
                var $this = $(this);
                $this.val("");
                if ($this.is("select")) {
                    var value = $this.find("option[Default-Value='1']").attr("value");
                    $this.val(value);
                }
                if ($this.attr('type') == 'checkbox')
                    $this.removeAttr('checked');

            });
            $("#FormEdit").find("[data-role='INSERT']").hide();
            if (CKEDITOR && CKEDITOR.instances["txtDescription_EN"])
                CKEDITOR.instances["txtDescription_EN"].setData('');
            if (CKEDITOR && CKEDITOR.instances["txtDescription_VN"])
                CKEDITOR.instances["txtDescription_VN"].setData('');
        }
    },
    Update: function (type, opts) {
        var thisObj = this;
        var data = {};
        switch (type) {
            case "INSERT":
            case "UPDATE":
                $("#FormEdit").find("[data-field]").each(function () {
                    var $this = $(this);
                    if ($this.attr("data-field")) {
                        var key = $this.attr("data-field");
                        var value = $this.val();
                        if ($this.attr('type') == 'checkbox') {
                            if ($this.is(':checked'))
                                value = 1;
                            else
                                value = 0;
                        }
                        data[key] = value;
                    }
                });
                break;
            case "DELETE":
            case "ACTIVE":
            case "DEACTIVE":
                data.ID = opts.ID;
                break;
            case "DELETEMULTI":
                data.IDs = opts.IDs;
                break;
        }
        data.ProductTypeID = ProductTypeID;
        data.Action = type;

        if (CKEDITOR && CKEDITOR.instances["txtDescription_EN"])
            data.Description_EN = CKEDITOR.instances["txtDescription_EN"].getData();
        if (CKEDITOR && CKEDITOR.instances["txtDescription_VN"])
            data.Description_VN = CKEDITOR.instances["txtDescription_VN"].getData();


        $.Ajax({
            url: '../Order/Service/OrderService.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    if (data.IsSuccessfull) {
                        thisObj.Grid.Reload();
                    }
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    Filter: function (type, opts) {
        var thisObj = this;
        var data = {};
        $("#FormFilter").find("[data-field]").each(function () {
            var $this = $(this);
            if ($this.attr("data-field")) {
                var key = $this.attr("data-field");
                var value = $this.val();
                if ($this.attr('type') == 'checkbox') {
                    if ($this.is(':checked'))
                        value = 1;
                }

                if ($this.attr("role") == "datepicker") {
                    value = $.CFormat.FormatDate(value, "yyyy/MM/dd HH:mm", "vi-VN", "en-US");
                }
                if (key == "Tags") {
                    if (value && $.isArray(value)) {
                        value = value.join(",");
                    }
                }
                data[key] = value;
            }
        });
        var url = '../Towntalk/Service/GetNewsList.ashx?Action=GET&Context=Backend';
        for (var key in data) {
            var attrName = key;
            var attrValue = data[key];
            if (attrValue == null)
                attrValue = "";
            url += $.string.Format("&{0}={1}", attrName, attrValue);
        }
        thisObj.Grid.SetNewUrl(url);

    },
    DialogFilter: {
        ID: "#FormFilter",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            thisObj.ClearForm();
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Tìm danh mục sản phẩm",
                    width: 300,
                    position: {
                        my: 'top',
                        at: 'top'
                    },
                    open: function () {
                    }
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "Tìm";

            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.Order.Filter(action, opts);
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Đóng",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },

        ClearForm: function () {
            $("#FormFilter").find("[data-field]").each(function () {
                var $this = $(this);
                $this.val("");
                if ($this.is("select")) {
                    var value = $this.find("option[Default-Value='1']").attr("value");
                    $this.val(value);
                }

            });
            $("#FormFilter").find("[data-role='INSERT']").hide();

            Axis.Admin.Order.DropdownChecklist.Clear();
        }
    },

    OrderDetail: function (type, opts) {
        var thisObj = this;
        var data = {};


    },
    DialogOrderDetail: {
        ID: "#OrderDetail",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            thisObj.ClearForm();
            thisObj.Update(opts);
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "OrderDetail",
                    width: 800,
                    position: {
                        my: 'top',
                        at: 'top'
                    },
                    open: function () {
                    }
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "Tìm";

            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                //Axis.Admin.Order.Filter(action, opts);
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Đóng",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        ClearForm: function () {
            $(".ItemDetail").remove();
            $("#TotalValue").html('');
            /*
            <tr height="25px" class="ItemDetail">
            <td style="padding-left: 10px">
            Acer 195HQ
            </td>
            <td align="center">
            2.350.000 VND
            </td>
            <td align="center">
            1
            </td>
            <td align="center">
            2.350.000 VND
            </td>
            </tr>*/

        },
        Update: function (opts) {
            var pData = { OrderID: opts.ID };
            $.ajax({
                url: 'Service/OrderDetailService.asmx/GetOrderDetail',
                type: 'POST',
                data: pData,
                cache: false,
                // contentType: "application/json; charset=utf-8",
                // dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    data = $(data).find("string").text();
                    var mas = eval("(" + data + ")");
                    var pattem = '<tr height="25px" class="ItemDetail">' +
                    '<td style="padding-left: 10px">{0}</td>' +
                    '<td align="center">{1} VND </td>' +
                    '<td align="center">{2}</td>' +
                    '<td align="center">{3} VND</td>' +
                    '</tr>';
                    var Summary = 0;
                    if (mas.length > 0) {
                        $.each(mas, function (index, item) {
                            var value = parseInt(item.Price) * parseInt(item.Quantity);
                            Summary += value;
                            $($.string.Format(pattem, item.Name, item.Price, item.Quantity, value)).insertAfter('#DetailHeader');
                        });
                    }
                    $("#TotalValue").html(Summary + " VND");
                    //DetailHeader
                    //overlay.Hide();
                },
                beforeSend: function (jqXHR, settings) {
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    //overlay.Hide();
                },
                complete: function (XMLHttpRequest, textStatus) {
                    //overlay.Hide();
                }
            });

        }
    },
      DeleteNews: function (id) { 
    var thisObj=this;
      var rowData = thisObj.Grid.SelectRow();
      if(typeof id!='undefined'){
            rowData=thisObj.Grid.GetRowData(id);
            if (rowData && rowData.ID) {
                $.CAlert.Confirm({
                    Title: "Xóa đơn đặt hàng",
                    Content: $.string.Format("Bạn có chắc muốn xóa đơn đặt hàng: [{0}].", rowData.Title),
                }, function (isOK) {
                    if (isOK)
                        thisObj.Update("DELETE", rowData);
                });
            }
            else {
                $.CAlert.Alert({
                    Title: "Xóa đơn đặt hàng",
                    Content: "Vui lòng chọn đơn đặt hàng cần xóa.",
                });
            }
    }
    else{
     $.CAlert.Confirm({
                    Title: "Xóa đơn đặt hàng",
                    Content: $.string.Format("Bạn có chắc muốn xóa đơn đặt hàng",''),
                }, function (isOK) {
                    if (isOK){
                   rowData.IDs= $(thisObj.Grid.ID).jqGrid('getGridParam','selarrrow').toString();
                        thisObj.Update("DELETEMULTI", rowData);
                        }
                });

        }
    }
   

};
$(function () {
    Axis.Admin.Order.Init();
    $("#QuantityAvailable").keydown(function (e) {
        var key = e.charCode || e.keyCode || 0;
        // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
        return (
			               key == 8
			            || key == 9
			            || key == 46
			            || (key >= 35 && key <= 40)
			            || (key >= 48 && key <= 57 && event.shiftKey == false)
			            || (key >= 96 && key <= 105));
    });
});
function ShowEdit(rowID) {
    var thisObj = Axis.Admin.Order;
    var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
    if (rowData && rowData.ID)
        thisObj.DialogEdit.Init("UPDATE", rowData);
}

function ShowOrderDetail(rowID) {
    var thisObj = Axis.Admin.Order;
    var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
    if (rowData && rowData.ID)
        thisObj.DialogOrderDetail.Init("UPDATE", rowData);
}

function DeleteNews(rowID) {
    Axis.Admin.Order.DeleteNews(rowID);
}
function FormatGridDescription(cellvalue, options, rowObject) {
    if (cellvalue.indexOf("project_desc_panel") == -1) {
        return '<div class="project_desc_panel">' + cellvalue + '</div>';
    }
    else
        return cellvalue;

}

function AddImage(ID) {
    window.location.assign('../Home/ProductImageList.aspx?ProductID=' + ID);
}


function ActionStatus(rowID, Status) {
    var thisObj = Axis.Admin.Order;
    var newStatus = "Active";
    var action = "DEACTIVE";
    Status = parseInt(Status);
    if (Status == 1) {
        newStatus = "DeActive";
        action = "ACTIVE";
    }
    if (Status == -1)
        return;
    var rowData = { ID: rowID };
    if (rowData && rowData.ID) {
        $.CAlert.Confirm({
            Title: "Cập nhật trạng thái danh mục sản phẩm",
            Content: $.string.Format("Bạn có chắc muốn thay đôi trạng thái danh mục sản phẩm", newStatus)
        }, function (isOK) {
            if (isOK)
                thisObj.Update(action, rowData);
        });
    }
    else {
        $.CAlert.Alert({
            Title: "Xóa danh mục sản phẩm",
            Content: "Vui lòng chọn danh mục sản phẩm cần xóa."
        });
    }
}

function ExportExcel(ID) {
    window.open('ExportExcel.aspx');
}
